<script lang="ts" setup>
import { useRequest } from 'vue-request'
import axios from 'axios'
import { reactive } from 'vue'

interface ReturnType {
  code: number
  data: {
    name: string
  }
}

interface ParamType {
  id: number
  name: string
}

function serviceMethod(param: ParamType): Promise<ReturnType> {
  return axios.post('/api/post', param)
}

function formatResult(ajaxResp: any): ReturnType | null {
  const { data } = ajaxResp
  return { code: data.code, data: data.data }
}

const { queries, run } = useRequest<any, ParamType[], ReturnType | null>(
  serviceMethod,
  {
    manual: true,
    queryKey: (reqData: ParamType) => String(reqData.id),
    formatResult,
  }
)

function onClick(id: number, name: string) {
  const p: ParamType = { id, name: name + new Date().toLocaleTimeString() }
  run(p)
  console.log('执行ajax请求')
}

const userListReactive = reactive([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
])
</script>

<template>
  <h3>并发请求(适用于列表页的操作按钮)：UseRequestDemo05.vue</h3>
  <div>
    <div v-for="oneUser in userListReactive" :key="oneUser.id">
      <button @click="() => onClick(oneUser.id, oneUser.name)">点我执行</button>
      {{ oneUser.name }}: ajax请求状态：{{
        queries[oneUser.id] && queries[oneUser.id].loading
      }}, 请求结果：{{ queries[oneUser.id] && queries[oneUser.id].data }}
    </div>
  </div>
</template>
